#include "queue.h"

char * dequeue( struct queue *queue ) 
{
	char *msg;
	struct queue_node *free_me_node = NULL;

	if ( queue->first != NULL ) {
		free_me_node = queue->first;
		msg = queue->first->msg;
		if ( queue->first == queue->last ) {
			queue->first = NULL;
			queue->last = queue->first;			
		}
		else 
			queue->first = queue->first->next;

		free( free_me_node );
		return msg;
	}	
	else
		return NULL;
}

int enqueue( struct queue *queue, char *msg ) 
{
	struct queue_node *node = ( struct queue_node *) malloc( sizeof( struct queue_node ) );
	if ( node == NULL ) {
		fprintf( stderr, "Queue node allocation failed, out of memory. \n" );
		return -1;	
	}

	node->msg = msg;
	if ( queue->first == NULL ) {
		queue->first = node;
		queue->last = queue->first;
	}
	else {
		queue->last->next = node;
		queue->last = node;
	}	
	queue->last->next = NULL;

	return 0;
}

bool queue_empty( struct queue *queue ) 
{
	return queue->first == NULL ? true : false;
}

int queue_size( struct queue *queue ) 
{
	/* Not implemented yet */
	return -1;
}

struct queue * new_queue() 
{
	struct queue *queue_t = ( struct queue *) malloc( sizeof( struct queue ) );

	if ( queue_t == NULL ) {
		fprintf( stderr, "Queue allocation failed, out of memory. \n" );		
		return NULL;
	}

	queue_t->first = NULL;
	queue_t->last	 = NULL;

	return queue_t;
}

void delete_queue( struct queue *queue )
{
	if ( queue != NULL ) {
		free( queue ); /* This is ok only when queue is empty, otherwise memory leaks occur
		TODO: check the size of queue and empty it. */
	}
}
